import ctypes
import sys
import os
import string
import win32file
import inspect
import datetime 
from datetime import date
from win32com.shell import shell, shellcon
from wx._misc import DropTarget, DataObject, MessageBox
from wxPython._controls import wxTextCtrl
import ConfigParser
from win32con import WM_DROPFILES, WM_COPYDATA
from win32com.client import Dispatch
from shutil import copyfile
from sqlalchemy.sql.functions import localtime
from adodbapi.adodbapi import Date, STRING
from winappdbg.win32.kernel32 import GetCurrentProcessId
from paramiko.sftp_attr import SFTPAttributes
from wx._controls import LIST_FORMAT_RIGHT, LIST_FORMAT_LEFT, LIST_FORMAT_CENTER
from Tkinter import EXCEPTION
from pickle import TRUE
from wx.lib.dialogs import DialogResults
from Pyrex.Compiler.PyrexTypes import typecast
sys.path = [os.getcwd()] + sys.path
import shutil
import webbrowser
import pythoncom
import wx.lib.mixins.listctrl as listmix 
import paramiko
import time
import threading
import urllib
import win32api
import win32con
from ctypes.wintypes import MAX_PATH
from win32com.client import GetObject
import subprocess
import socket
import zipfile
import ftplib
import MySQLdb
import CustomFlatnotepad as cfn

import re
import wx.lib.agw.buttonpanel as bp
from wx.lib.stattext import GenStaticText as StaticText
import wx.lib.agw.gradientbutton as GB
import wx
from wx import aui


class FileDrop(wx.FileDropTarget):
    def __init__(self, master, window):
        wx.FileDropTarget.__init__(self)
        self.window = window
        self.master = master

    def OnDropFiles(self, x, y, filenames):
        self.master.filepath = []
        for name in filenames:
            try:
                self.master.filepath.append(name)
            except Exception, e:
                wx.MessageBox('Cannot send this file !', 'Error !', wx.OK)
        self.master.ProcessSendFile()

class MyTextCtrl(wx.TextCtrl):
    def __init__(self,parent,id,value="",pos=wx.DefaultPosition,size=wx.DefaultSize,style=0):
        try:
            wx.TextCtrl.__init__(self,parent,id,value,pos,size,style)
            
            self.master = parent
            self.size = self.GetSize()
            self.charset = 'euc-kr'
            self.save_insert = 0
            self.sendfile = 0
            self.rowpaper = 40
            self.colpaper = 112
            self.downPoint = -1  
            self.upPoint = -1 
            self.previousPoint = -1
            self.trend = 1
            self.trendFlag = False
            self.pwd = None
            self.textValue = ''
            
            
            
            self.fontn = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, face="INCONSOLATA", encoding=wx.FONTENCODING_DEFAULT)
            self.fontb = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, face="INCONSOLATA" , encoding=wx.FONTENCODING_DEFAULT)

            
            self.SetDropTarget(wx.PyDropTarget())            
            self.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)
            self.SetFont(self.fontn)
            
            self.list_of_paintables = []
            
            self.Bind(wx.EVT_MOUSE_CAPTURE_CHANGED, self.mouse)
            self.Bind(wx.EVT_SCROLLBAR, self.mouse)
            self.Bind(wx.EVT_MOUSE_EVENTS, self.mouser_event)
            self.Bind(wx.EVT_LEFT_DCLICK, self.mouse)
            self.Bind(wx.EVT_LEFT_DOWN, self.leftdown)
            self.Bind(wx.EVT_LEFT_UP, self.leftup)
            self.Bind(wx.EVT_CHAR, self.key)
            self.Bind(wx.EVT_KEY_DOWN, self.onBack)
            
            self.SetInsertionPoint(0)
            self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
            
            self.insert_temp = self.GetLastPosition()
            
            self.indexText = self.GetLastPosition()
            
            wx.CallAfter(self.SetInsertionPoint, self.indexText)
            
            self.Bind(wx.EVT_SIZE, self.OnSize)

            dt = FileDrop(self.master, self)
            self.SetDropTarget(dt)
            
        except Exception, e:
            print "loi o day"
            print e
    
    def OnSize(self, evt):
        # for normal size events
        self.isresize = True
#        self.text.SetInsertionPoint(self.text.GetInsertionPoint())
        self.SetFocus()
        evt.Skip()
    
    def OnContextMenu(self, event):
        if self.isconnect == False:
            return

        if not hasattr(self, "popupID1"):
            self.popupID1 = wx.NewId()
            self.popupID2 = wx.NewId()
            self.popupID3 = wx.NewId()
            self.popupID4 = wx.NewId()
            self.popupID5 = wx.NewId()
            self.popupID6 = wx.NewId()
            self.popupID7 = wx.NewId()
            self.popupID8 = wx.NewId()
            
            self.Bind(wx.EVT_MENU, self.OnCopy, id=self.popupID1)
            self.Bind(wx.EVT_MENU, self.OnPaste, id=self.popupID2)
            self.Bind(wx.EVT_MENU, self.OnCopyAPaste, id=self.popupID3)
            self.Bind(wx.EVT_MENU, self.OnOpenURL, id=self.popupID4)
            self.Bind(wx.EVT_MENU, self.OnFind, id=self.popupID5)
            self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupID6)
            self.Bind(wx.EVT_MENU, self.OnClearScrollback, id=self.popupID7)
            self.Bind(wx.EVT_MENU, self.OnClearScreen, id=self.popupID8)
            


        # make a menu
        self.menupopup = wx.Menu()
        # Show how to put an icon in the menu
        
        
        item = wx.MenuItem(self.menupopup, self.popupID1, "Copy")
        self.menupopup.AppendItem(item)
        
        item = wx.MenuItem(self.menupopup, self.popupID2, "Paste")
        self.menupopup.AppendItem(item)
        
        item = wx.MenuItem(self.menupopup, self.popupID3, "Copy && Paste")
        self.menupopup.AppendItem(item)
        
        self.menupopup.AppendSeparator()
        
        item = wx.MenuItem(self.menupopup, self.popupID4, "Open URL")
        self.menupopup.AppendItem(item)
        
        self.menupopup.AppendSeparator()
        
        item = wx.MenuItem(self.menupopup, self.popupID5, "Find...")
        self.menupopup.AppendItem(item)
        
        item = wx.MenuItem(self.menupopup, self.popupID6, "Select All")
        self.menupopup.AppendItem(item)
        
        self.menupopup.AppendSeparator()
        
        item = wx.MenuItem(self.menupopup, self.popupID7, "Clear Scrollback")
        self.menupopup.AppendItem(item)
        
        item = wx.MenuItem(self.menupopup, self.popupID8, "Clear Screen")

        self.menupopup.AppendItem(item)

        
        self.UpdateStatusPopupMN()
        self.PopupMenu(self.menupopup)
        self.menupopup.Destroy()
    
    def OnCopyAPaste(self, event):
        self.OnCopyAndPaste(None)
        
    def OnOpenURL(self, event):
        webbrowser.open(self.link)
        
    
    def OnFind(self, event):

        if self.flagFindDialog:
            self.flagFindDialog = False
            self.downPoint = self.GetInsertionPoint()
            self.upPoint = self.GetInsertionPoint()
            self.finddata = wx.FindReplaceData()
            self.findDlg = wx.FindReplaceDialog(self.master, self.finddata, "Find")
            self.findDlg.data = self.finddata  # save a reference to it...
            self.findDlg.Show(True)
            self.indexfind = self.GetInsertionPoint()
        else:
            self.findDlg.SetFocus()
    
    def OnSelectAll(self, event):
        self.downPoint = 0
        self.upPoint = self.GetLastPosition()
        self.SetStyle(self.downPoint, self.upPoint, wx.TextAttr(wx.NullColour, '#3399ff', self.fontb))


    
    def OnClearScrollback(self, event):
        if self.frow < 2:
            return
        self.updatePosition(0, self.frow)
        
    
    def OnClearScreen(self, event):
        self.AppendText('\n' * self.rowpaper)
        indexrow = self.GetNumberOfLines() - self.rowpaper
        self.SetInsertionPoint(self.XYToPosition(0, indexrow))
        if self.NumberOfLines > self.rowpaper:
            self.frow = self.NumberOfLines - self.rowpaper
            #####print 'frow....tinh...', self.text.NumberOfLines, self.rowpaper
        else:
            self.frow = 0
      
    def OnCopy(self, event):
        if not wx.TheClipboard.IsOpened():
            wx.TheClipboard.Open()
            do = wx.TextDataObject()
            if self.downPoint < self.upPoint:
                ###print self.text.GetRange(self.downPoint, self.upPoint)
                do.SetText(self.GetRange(self.downPoint, self.upPoint))
            else:
                ###print self.text.GetRange(self.downPoint, self.upPoint)
                do.SetText(self.GetRange(self.upPoint, self.downPoint))
            wx.TheClipboard.SetData(do)
            wx.TheClipboard.Close()
    
    def OnPaste(self, event):
        if not wx.TheClipboard.IsOpened():
            wx.TheClipboard.Open()
            do = wx.TextDataObject()
            wx.TheClipboard.GetData(do)
            self.channel.send(do.GetText())
            wx.TheClipboard.Close()  

    
    def OnCopyAndPaste(self, event): 
        if not wx.TheClipboard.IsOpened():
            wx.TheClipboard.Open()
            do = wx.TextDataObject()
            if self.downPoint < self.upPoint:
                ###print self.text.GetRange(self.downPoint, self.upPoint)
                do.SetText(self.GetRange(self.downPoint, self.upPoint))
            else:
                ###print self.text.GetRange(self.downPoint, self.upPoint)
                do.SetText(self.GetRange(self.upPoint, self.downPoint))
            wx.TheClipboard.SetData(do)  
            self.channel.send(do.GetText())
            wx.TheClipboard.Close() 
    
    def UpdateStatusPopupMN(self):
        if not wx.TheClipboard.IsOpened():  # may crash, otherwise
            do = wx.TextDataObject()
            wx.TheClipboard.Open()
            success = wx.TheClipboard.GetData(do)
            wx.TheClipboard.Close()
            self.menupopup.FindItemById(self.popupID2).Enable(success)
            ######print self.text.GetStringSelection()
            if self.downPoint == -1 or self.upPoint == -1 or self.downPoint == self.upPoint:
                self.menupopup.FindItemById(self.popupID1).Enable(False)
                self.menupopup.FindItemById(self.popupID3).Enable(False)
            else:
                self.menupopup.FindItemById(self.popupID1).Enable(True)
                self.menupopup.FindItemById(self.popupID3).Enable(True)
        
        if not self.flagLink:
            self.menupopup.FindItemById(self.popupID4).Enable(True)
        else:
            self.menupopup.FindItemById(self.popupID4).Enable(False)
    
    def leftdown(self, event):  
    
        self.Freeze()
        currentScroll = self.GetScrollPos(wx.VERTICAL)
        if self.upPoint > -1:
            self.SetStyle(self.downPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
        while currentScroll < self.GetScrollPos(wx.VERTICAL):
        
            self.ScrollLines(-1)
              
        while currentScroll > self.GetScrollPos(wx.VERTICAL):
        
            self.ScrollLines(1)
            if currentScroll == self.GetScrollPos(wx.VERTICAL) + 1:
                break
        self.Thaw()
            
        self.Freeze()
        self.top_data.drag()
        event.Skip()
        return   
        self.trendFlag = True    
        currentScroll = self.GetScrollPos(wx.VERTICAL)
        
        self.Freeze()
        
        (res, downPoint) = self.HitTestPos(event.GetPosition())
        if self.upPoint > -1:
            self.SetStyle(self.downPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
#       
        while currentScroll < self.GetScrollPos(wx.VERTICAL):
        
            self.ScrollLines(-1)
              
        while currentScroll > self.GetScrollPos(wx.VERTICAL):
        
            self.ScrollLines(1)
        self.Thaw()  
        
        self.upPoint = -1 
        self.previousPoint = -1
        self.trend = 1
        self.previousPoint = downPoint
        self.downPoint = downPoint
         
        self.trendFlag = False       
        return
        
    
    def leftup(self, event):
        event.Skip()
        self.master.top_data.drop() 
        return      
    
    def onBack(self, event):
        keycode = event.GetKeyCode()
       
        if keycode == wx.WXK_TAB:            
            self.channel.send(chr(keycode))
            return
        elif keycode == wx.WXK_F2:
            self.top_data.delay()
        elif keycode == wx.WXK_F1:
            try:

                pos = self.GetScrollPos(wx.VERTICAL)
                print pos
                self.SetStyle(0, 10, (wx.TextAttr(wx.NullColour, 'BLUE', self.fontb)))
                
                while pos < self.GetScrollPos(wx.VERTICAL):
                    self.ScrollLines(-1)
                return
                self.ScrollLines(-1)
            except Exception, e:
                pass
            
        elif keycode == wx.WXK_BACK:
            self.OnDisBksp(event)
        elif self.connected == False:
                return 'break'
        elif keycode == wx.WXK_UP:
            self.OnDisUp(event)
        elif keycode == wx.WXK_DOWN:
            self.OnDisDown(event)
        elif keycode == wx.WXK_LEFT:
            self.OnDisLeft(event)
        elif keycode == wx.WXK_RIGHT:
            self.OnDisRight(event)
        elif keycode == wx.WXK_DELETE:
            self.OnDisDelete(event)
        elif keycode == wx.WXK_RETURN:
            if self.dynamis_name == 'COMMAND':
                self.channel.send(chr(keycode))
                return
            else:
                return
        elif event.ControlDown() == True and keycode == 82:
            self.channel.send(chr(18))
            return
        elif (event.ControlDown() == True and keycode == 90) or (event.ControlDown() == True and keycode == 68):

            if self.top_data != None:
                self.channel.send(chr(keycode - 64))
                self.comments_temp = keycode
                return 'break'
            else:
                return
        elif (event.ControlDown() == True and keycode == 82) :
            ###print 'vao day'
            self.channel.send(chr(keycode - 64))
            self.comments_temp = keycode
            return 'break'
        elif (event.ControlDown() == True and keycode == 76) :
            self.channel.send(chr(keycode - 64))
            self.comments_temp = keycode
            return 'break'  
        elif (event.ControlDown() == True and (keycode == 69 or keycode == 65 or keycode == 86 or keycode == 67)) :
            self.channel.send(chr(keycode - 64))
            self.comments_temp = keycode
            return 'break'   
        elif keycode == 27:
            
            if self.top_data != None :
                self.channel.send(chr(27))
                self.comments_temp = keycode
                return 'break'
            else:
                return
        else:

            event.Skip()
    
    def OnDisUp(self, event):
        if self.dynamis_name == 'VI':
            #####print "upvi"
            self.keypress = 'up'
            #####print 'OnDisUp'
            event.Skip()

        elif self.dynamis_name == 'COMMAND': 
            self.channel.send('OA')
            return 
        
        else:
            return 'break'

    def OnDisDown(self, event):
   
  
        if self.dynamis_name == 'COMMAND': 
            self.channel.send('OB')
            return 
        
        else:
            return 'break'
    
    def OnDisLeft(self, event):
#        self.update_insert()
        if self.dynamis_name == 'COMMAND':
            self.channel.send('OD')
            return
        
        else:
            return
    
    def OnDisRight(self, event):
#        self.update_insert()
        if self.dynamis_name == 'COMMAND':
            self.channel.send('OC')
            return
        

        else:
            return
    
    def OnDisBksp(self, event):
#        self.update_insert()
        if self.dynamis_name == 'COMMAND':
            self.channel.send(chr(wx.WXK_BACK))
            return
        
    
        else:
            return
    
    def OnDisDelete(self, event):        
#        self.update_insert()
        ######print 'OnDisDelete'
        if self.dynamis_name == 'COMMAND':
            self.channel.send(chr(wx.WXK_DELETE))
            return
        
     
        else:
            return
    
    def key(self, event):
        try:

            keycode = event.GetKeyCode()


            if self.dynamis_name == 'COMMAND':
                if keycode == 97:

                    pass
                if keycode < 257:
                    self.channel.send(chr(keycode))
                return  
            else:
                return

        except Exception, e:
            pass
        finally:
            pass 
            
    def mouse(self, event):
        if self.dynamis_name == 'TOP':
            return 'break'
        elif self.dynamis_name == "VI" and self.VIlevel == 3:
            return 'break'
        
        else:
            return
            event.Skip()
    
    def mouser_event(self, event):
        event.Skip()
        return
        if event.Leaving():
            self.top_data.drag()
            
        if event.RightIsDown():

            hit, indexclick = self.HitTestPos(event.GetPosition())
            x, y = self.PositionToXY(indexclick)
            indexx = x
            linetext = self.GetLineText(y)
            
            link = None
            strings = linetext.split(' ')
            lengindex = 0
            for i in range(len(strings)):
                lengindex = lengindex + strings[i].__len__() + 1
                if lengindex - 1 >= x:
                    x = x - (lengindex - strings[i].__len__())
                    lengindex = i
                    break
            #print strings[lengindex]
            if indexx + 5 > len(linetext) - 1:
                linelink = strings[lengindex][:x]
            else:
                linelink = strings[lengindex][:x + 5]
            seal = re.search(r'www.', linelink)
            if seal != None:
                pass
            else:
                seal = re.search(r'ftp://', linelink)
                if seal != None:
                    pass
                else:
                    seal = re.search(r'http://', linelink)
                    if seal != None:
                        pass
                    else:
                        seal = re.search(r'https://', linelink)
                        
            if seal != None:
                seal = seal.start()
                link = strings[lengindex][seal:]

            if link != None:
                self.flagLink = False
                self.link = link
            else:
                self.flagLink = True
                self.link = ""
      
        #################################################
        
        
        if event.Dragging() and event.LeftIsDown(): 
            if self.trendFlag == False and self.downPoint != -1:
                self.trendFlag = True
                hit, self.upPoint = self.HitTestPos(event.GetPosition())
                mouse1 = self.upPoint
                self.Freeze()
                currentScroll = self.GetScrollPos(wx.VERTICAL)
                if self.upPoint > self.downPoint:
                    #print 'if',currentScroll
                    if self.previousPoint == -1:
                        self.SetStyle(self.downPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'CYAN', self.fontb)))
                    else:
                        if self.previousPoint < self.downPoint:
                            self.SetStyle(self.previousPoint, self.downPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
                            self.previousPoint = self.downPoint
                        if self.previousPoint < self.upPoint:
                            self.SetStyle(self.previousPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'CYAN', self.fontb)))
                        elif self.previousPoint > self.upPoint:
                            self.SetStyle(self.previousPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
                        else:
                            pass
                            
                elif self.upPoint < self.downPoint:
                    if self.previousPoint == -1:
                        self.SetStyle(self.downPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'CYAN', self.fontb)))
                    else:
                        if self.previousPoint > self.downPoint:
                            self.SetStyle(self.downPoint , self.previousPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
                            self.previousPoint = self.downPoint
                            
                        if self.previousPoint > self.upPoint:
                            self.SetStyle(self.previousPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'CYAN', self.fontb)))
                        elif self.previousPoint < self.upPoint:
                            self.SetStyle(self.previousPoint, self.upPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
                        else:
                            
                            pass    
                else:
                    if self.previousPoint != -1:
                        self.SetStyle(self.previousPoint, self.downPoint, (wx.TextAttr(wx.NullColour, 'WHITE', self.fontb)))
                    else:
                        pass
                while currentScroll < self.GetScrollPos(wx.VERTICAL):
                    self.ScrollLines(-1)
                      
                while currentScroll > self.GetScrollPos(wx.VERTICAL):
                    self.ScrollLines(1)
                            
                self.Thaw()
                if mouse1 != self.upPoint:
                    
                    pass
                self.previousPoint = self.upPoint
                event.Skip()
                self.trendFlag = False
                return
            
        event.Skip()
        return

class SSH(wx.Frame):
    def __init__(self, shadesubmenus=False):
        try:
            wx.Frame.__init__(self, None, -1, 'Elisoft CRT', size=(900, 700))
            self.SetMinSize((650, 500))
            self.SetTitle('Elisoft CRT ' + self.readVersion('update_version.ini'))
            #Xu ly icon
            #tsize = (24,24)
            self.flagFindDialog = True
            self.nBytes = 0;
            self.new_bmp = wx.Bitmap("image/new.png", wx.BITMAP_TYPE_PNG)
            self.edit_bmp = wx.Bitmap("image/edit.png", wx.BITMAP_TYPE_PNG)
            self.connect_bmp = wx.Bitmap("image/connect.png", wx.BITMAP_TYPE_PNG)
            self.disconnect_bmp = wx.Bitmap("image/disconnect.png", wx.BITMAP_TYPE_PNG)
            self.delete_bmp = wx.Bitmap("image/Delete.png", wx.BITMAP_TYPE_PNG)
            self.quit_bmp = wx.Bitmap("image/quit.png", wx.BITMAP_TYPE_PNG)
            self.update_bmp = wx.Bitmap("image/update.png", wx.BITMAP_TYPE_PNG)
            self.sendfile_bmp = wx.Bitmap("image/send_file.png", wx.BITMAP_TYPE_PNG)
            self.setting_bmp = wx.Bitmap("image/setting.png", wx.BITMAP_TYPE_PNG)
            self.notepad_bmp = wx.Bitmap("image/notepad.png", wx.BITMAP_TYPE_PNG)
            
            #Create menuitem
            self.menuFile = wx.Menu()
            item = wx.MenuItem(self.menuFile, 1, "Connect")
            item.SetBitmap(self.connect_bmp)
            self.menuFile.AppendItem(item)

            item = wx.MenuItem(self.menuFile, 2, "Disconnect")
            item.SetBitmap(self.delete_bmp)
            self.menuFile.AppendItem(item)

            self.menuFile.AppendSeparator()
            
            item = wx.MenuItem(self.menuFile, 3, "Exit")
            item.SetBitmap(self.quit_bmp)
            self.menuFile.AppendItem(item)
            
            self.menuOption = wx.Menu()
            item = wx.MenuItem(self.menuOption, 6, "Setting")
            item.SetBitmap(self.setting_bmp)
            self.menuOption.AppendItem(item)

            self.menuProcess = wx.Menu()
            item = wx.MenuItem(self.menuProcess, 4, "Send File")
            item.SetBitmap(self.sendfile_bmp)
            self.menuProcess.AppendItem(item)

            self.menuScript = wx.Menu()
            item = wx.MenuItem(self.menuScript, 5, "Run Script")
            item.SetBitmap(self.update_bmp)
            self.menuScript.AppendItem(item)
            
            icon = wx.Icon("image/house_16.ico", wx.BITMAP_TYPE_ICO, 16, 16)
            self.SetIcon(icon)
            
            
            item = self.menuFile.FindItemById(2)
            item.Enable(False)
            
            #Create menubar & statusbar
            self.menuBar = wx.MenuBar()
            self.menuBar.Append(self.menuFile, "File")
            self.menuBar.Append(self.menuProcess, "Process")
            self.menuBar.Append(self.menuScript, "Script")
            
            self.SetMenuBar(self.menuBar)
            
            self.statusbar = self.CreateStatusBar()
            self.statusbar.SetFieldsCount(7)
            self.SetStatusWidths([-1, 50, 50, 100, 50, 30, 60])
            self.statusbar.sizeChanged = False

            self.statusbar.Bind(wx.EVT_IDLE, self.OnIdle)
            
            
            self.statusbar.SetStatusText("A Custom StatusBar...", 0)
            self.statusbar.SetStatusText("", 1)
            self.statusbar.SetStatusText("", 2)
            self.statusbar.SetStatusText("", 3)
            self.statusbar.SetStatusText("", 4)
            self.statusbar.SetStatusText("", 5)
            self.statusbar.SetStatusText("", 6)

            

            #Action menuitem
#            #self.Bind(wx.EVT_MENU, self.OnConnect, id=1)
#            #self.Bind(wx.EVT_MENU, self.OnDisconnect, id=2)
#            #self.Bind(wx.EVT_MENU, self.OnExit, id=3)
#            #self.Bind(wx.EVT_MENU, self.OnSendFile, id=4)
#            #self.Bind(wx.EVT_MENU, self.OnRunScript, id=5)
#            ##self.Bind(wx.EVT_MENU, self.OnSetting, id=6)
#            
#            #self.Bind(wx.EVT_FIND, self.OnFindAct)
#            #self.Bind(wx.EVT_FIND_NEXT, self.OnFindAct)
#            #self.Bind(wx.EVT_FIND_REPLACE, self.OnFindAct)
#            #self.Bind(wx.EVT_FIND_REPLACE_ALL, self.OnFindAct)
#            #self.Bind(wx.EVT_FIND_CLOSE, self.OnFindClose)
#            #self.Bind(wx.EVT_CLOSE, self.OnClose)
            #Create toolbar
            self.panel = wx.Panel(self, -1)
            self.box = wx.BoxSizer(wx.VERTICAL)
            #self.box = wx.BoxSizer(wx.HORIZONTAL)
            self.panel.SetSizer(self.box)
            self.panel.SetAutoLayout(True) 
            
            self.toolbar = bp.ButtonPanel(self.panel, -1, "",
                                          agwStyle=bp.BP_USE_GRADIENT, alignment=bp.BP_ALIGN_LEFT)
            
            self.box.Add(self.toolbar, 0, wx.EXPAND)
            
            bpArt = self.toolbar.GetBPArt()
            bpArt.SetColour(bp.BP_BORDER_COLOUR, wx.Colour(229, 229, 229))
            bpArt.SetColour(bp.BP_GRADIENT_COLOUR_FROM, wx.Colour(229, 229, 229))
            bpArt.SetColour(bp.BP_GRADIENT_COLOUR_TO, wx.Colour(229, 229, 229))
            bpArt.SetColour(bp.BP_BUTTONTEXT_COLOUR, wx.Colour(0, 0, 0))
            bpArt.SetColour(bp.BP_SEPARATOR_COLOUR,
                            bp.BrightenColour(wx.Colour(60, 11, 112), 0.85))
            bpArt.SetColour(bp.BP_SELECTION_BRUSH_COLOUR, wx.Colour(255, 255, 255))
            bpArt.SetColour(bp.BP_SELECTION_PEN_COLOUR, wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION))
           

            
            self.btnconnect = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.connect_bmp, text='  Connect  ',
                                shortHelp='Connect')
            self.toolbar.AddButton(self.btnconnect)
            #self.Bind(wx.EVT_BUTTON, self.OnConnect, id=self.btnconnect.GetId())

            self.btndisconnect = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.delete_bmp, text='Disconnect',
                                shortHelp='Disconnect')
            self.toolbar.AddButton(self.btndisconnect)
            #self.Bind(wx.EVT_BUTTON, self.OnDisconnect, id=self.btndisconnect.GetId())
            self.btndisconnect.Enable(False)
            self.toolbar.AddSeparator()
            
            self.btnsend = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.sendfile_bmp, text='      Send     ',
                                shortHelp='Send')
            self.toolbar.AddButton(self.btnsend)
            ###########################################
            #self.Bind(wx.EVT_BUTTON, self.OnSendFile, id=self.btnsend.GetId())
            self.btnsend.Enable(False)
            
            #########################MinhTuan-SendFileNew
            self.btnsendNew = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.sendfile_bmp,text='      Send     ',
                                shortHelp='Send')
            self.toolbar.AddButton(self.btnsendNew)
            ###########################################
            #self.Bind(wx.EVT_BUTTON, self.OnSendFileNew, id=self.btnsendNew.GetId())
            self.btnsendNew.Enable(False)            
            ########################
            
            self.toolbar.AddSeparator()
            
            self.btnNotepad = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.notepad_bmp, text='Notepad',
                                shortHelp='Notepad')
            self.toolbar.AddButton(self.btnNotepad)
            #self.Bind(wx.EVT_BUTTON, self.OnNotePad, id=self.btnNotepad.GetId())
            self.btnNotepad.Enable(False)
            self.toolbar.AddSeparator()
      
            btn = bp.ButtonInfo(self.toolbar, wx.NewId(),
                                self.quit_bmp, text='      Exit     ',
                                shortHelp='Exit')
            self.Bind(wx.EVT_BUTTON, self.OnTest, id=btn.GetId())
            
            self.toolbar.AddButton(btn)
            self.toolbar.DoLayout()
            
            self.nb = cfn.CustomsFlatNotebook(self.panel,size=(800,600),style=wx.BORDER_NONE )
            
            self.text = wx.TextCtrl(self.nb, -1, "Text Control\n", style=wx.TE_MULTILINE | wx.TE_RICH2)
            self.nb.AddPage(self.text, "Welcome")
            self.box.Add(self.nb, 1, wx.EXPAND)
            
            self.text2 = wx.TextCtrl(self.nb, -1, "Text Control\n", style=wx.TE_MULTILINE | wx.TE_RICH2)
            self.nb.AddPage(self.text2, "Welcome2")                
            self.settingForBeginning()

             
        except Exception, e:
            ######print type(e)
            print e
            return
        
    def OnTest(self,event):
        print self.nb.GetPage(self.nb.GetSelection()).GetValue()
        
    def getPathDocument(self):
        dll = ctypes.windll.shell32
        buf = ctypes.create_unicode_buffer(MAX_PATH + 1)
        if dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False):
            return buf.value
        else:
            return None
        
    def settingForBeginning(self):
        
        self.indexfind = 0
        self.link = None
        self.flagLink = True
        self.flagFindDialog = True
        self.runScript = False
        self.flagfocus = True
        self.startSendFile = True
        self.indexFile = 0
        self.numofFile = 0
        self.file = None
        #command VI
        self.down = 0
        self.up = 0
        self.pointsave = 0
        self.codeteamp = ''
        self.commanddd = False
        self.charpressd = False
        #self.firstrun = False
        self.xtemp = 0
        self.ytemp = 0
        self.VIlevel = 2
        self.frow = 0
        self.numflaginsert = 0
        self.flagonsize = True
        
        self.numend = 0
        self.numstart = 0
        
        #self.firstrun = True
        self.keypress = ''
        self.flaginsert = True
        #self.flagVI = True
        self.numstop = 1
        self.stoppoint = True
        self.rowdel = 0
        self.row = 0
        self.col = 0
        self.rowpaper = 0
        self.colpaper = 0
        self.flagcolor = False
        #statusbar
        self.statusbar.SetStatusText("", 1)
        self.statusbar.SetStatusText("", 2)
        self.statusbar.SetStatusText("", 3)
        self.statusbar.SetStatusText("", 4)
        self.statusbar.SetStatusText("", 5)
        self.statusbar.SetStatusText("", 6)
        #connection
        self.isresize = False
        self.term = 'vt100'
        self.size = 65536 
        self.listconnections = []
        self.namecn = ''
        self.hostnamecn = ''
        self.usernamecn = ''
        self.pwcn = ''
        self.port = 22
        self.currentItem = -1
        self.connected = False   
        self.co = 0       
        self.accept_host = ''
        self.filepath = ''
        ######print 'setttingForBeginning'
        # Param of SSH
        self.namecn = ""
        self.hostnamecn = ""
        self.usenamecn = ""
        self.pwcn = ""
        self.portcn = 22
        
        self.command = "ssh> "
        self.len_command = 0
        self.length_char = 0
        self.processing = False
        self.disable_text = ""
        self.char_last_text = ""
        self.msg_edit = ""
        self.msg = ""
        self.cmd = ""
        self.contents = ""
        self.contents2 = ""
        self.comments = ""
        self.comments_temp = ""
        self.previous_command = ""
        self.top_data = None
        self.sh_top_data = None
        #self.ipaddress = self.getPublicIp()
        self.current_folder = "."
        self.connect_folder = ""
        self.accept_login = ''
        self.locate = 'ssh> '
        self.path = 'abcd'
        self.sh_locate = ''
        self.flag_command = False
        self.returnCommand = False

        #Param of dynamis
        self.channel = None
        self.dynamis_name = None
        
        self.topIndex = 1.0
        self.endIndex = 1.0
        self.filename = ""
        self.waiting = False
        self.temp_store = []
        self.temp_lenght = -1
        self.tempArray = []
        self.vi_default = ['exit', 'qcr', 'q', 'Q', '!q', 'wq', 'x']
        self.lenght = 1
        self.press_key = False

        #Param of SFTP
        self.sftp_host = ''
        self.sftp_port = 22
        self.sftp_username = ''
        self.sftp_password = ''
        self.sftp_msg = ''
        self.sftp_process = False
        self.sftp_check_password = False
        self.sftp_check_login = False
        self.sftp_maintain = False
        self.stdin = None
        self.stdout = None
        self.sftp = None

        # Variable Configure
        #self.text.config(state=Tkinter.DISABLED)
        self.fileopen = self.getPathDocument() + r"\py_ssh.data"
        
        #self.current_work = ""
        self.numkeywait = 0
        self.editmode = False
        self.listBold = []
        self.command_store = []
        self.sh_command_store = []
        self.command_key = -1
        self.input_command_len = 0
        self.disleft = False
    
    def OnIdle(self, evt):
        return
        if self.flagFindDialog:
            self.text.SetFocus()
        
        if self.isconnect:
            
            if self.isresize == True:
                #####print float(self.panel.GetSize().y-self.toolbar.GetSize().y-22)/float(self.text.GetCharHeight()) + 2.0
                
                
                rowpaper = float(self.panel.GetSize().y - self.toolbar.GetSize().y - 22) / float(self.text.GetCharHeight()) + 2.0
                mod = rowpaper - int(rowpaper)
                ##print 'mod...', mod
                ##print 'row...',rowpaper
                if mod < 0.6:
                    rowpaper -= 1
                rowpaper = int(rowpaper)
                colpaper = self.text.GetSize().x / self.text.GetCharWidth() + 2
                self.channel.resize_pty(width=colpaper, height=rowpaper)
                self.rowpaper = rowpaper 
                self.colpaper = colpaper
                self.numend = self.rowpaper
                self.isresize = False
                self.UpdateStatusBar3()
        
    def readVersion(self, pathFile):
        file = ConfigParser.RawConfigParser(allow_no_value=True)
        try:
            file.read(pathFile)
        except Exception, e:
            return ''
        arrRoot = file.sections()
        if len(arrRoot) > 0:
            for nodeRoot in arrRoot:
                if nodeRoot == 'SSHClient_WX.exe':
                    arrKeys = file.options(nodeRoot)
                    if len(arrKeys) > 0:
                        return file.get(nodeRoot, 'date')[:8]
        
        return ''
        
if __name__ == '__main__':
    try:
        bShadeSubMenus = sys.argv[1]
    except:
        bShadeSubMenus = False
    
    app = wx.PySimpleApp()
    root = SSH(shadesubmenus=bShadeSubMenus)
    root.Show()
    app.MainLoop()
